import {
	HTTP_IMG_URL,
	HTTP_REQUEST_URL,
} from '@/config/app';
import store from '@/store';
export function imageCompres(url) {
	return new Promise((resolve, reject) => {
		// 判断平台
		if (process.env.UNI_PLATFORM === 'h5') {
			// ✅ H5端
			const img = new Image();
			img.crossOrigin = "Anonymous";
			img.src = url;
			img.onload = () => {
				const canvas = document.createElement('canvas');
				const context = canvas.getContext('2d');
				let cw = img.width;
				let ch = img.height;
				let w = cw;
				let h = ch;
				if (cw > 600 || ch > 600) {
					if (cw > ch) {
						w = 600;
						h = (600 * ch) / cw;
					} else {
						h = 600;
						w = (600 * cw) / ch;
					}
				}
				canvas.width = w;
				canvas.height = h;
				context.drawImage(img, 0, 0, w, h);
				const base64 = canvas.toDataURL('image/jpeg', 0.8);
				resolve(base64);
			};
			img.onerror = err => {
				console.error("H5端图片加载失败:", err);
				reject(err);
			};
		} else {
			// ✅ App端
			const tempFileName = `${Date.now()}.jpg`;
			// 使用 compressImage 压缩图片
			uni.compressImage({
				src: url,
				quality: 80,
				success(res) {
					const compressedPath = res.tempFilePath;
					console.log("压缩后地址：", compressedPath);
					// 转换成 base64
					plus.io.resolveLocalFileSystemURL(compressedPath, (entry) => {
						entry.file((file) => {
							const reader = new plus.io.FileReader();
							reader.onloadend = function() {
								// 返回完整 base64 字符串
								if (!reader.result.startsWith('data:image')) {
									reader.result = 'data:image/jpeg;base64,' + reader.result;
								}
								resolve(reader.result);
							};
							reader.onerror = function(err) {
								console.error('读取文件失败', err);
								reject(err);
							};
							reader.readAsDataURL(file); // 读取为 base64
						}, (err) => {
							console.error('读取文件失败:', err);
							reject(err);
						});
					}, (err) => {
						console.error('解析路径失败:', err);
						reject(err);
					});
				},
				fail(err) {
					console.error("App端图片压缩失败:", err);
					reject(err);
				}
			});
		}
	});
};
//图片上传方法
export function uploadFilePromise(file) {
	uni.showLoading({
		title: '上传中...',
		mask: true
	});
	const token = store.state.app.token;
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: HTTP_REQUEST_URL + '/api/common/upload', // 仅为示例，非真实的接口地址
			filePath: file,
			header: {
				token: token
			},
			name: 'file',
			success: (res) => {
				let response = JSON.parse(res.data)
				if (response.code == 1) {
					setTimeout(() => {
						resolve(response.data)
						uni.hideLoading()
					}, 1000)
				} else {
					uni.showToast({
						title: response.msg,
						icon: 'none'
					})
					uni.hideLoading()
				}
			},
		});
	})
}
/**
 * @desc 拼接OSS图片地址  
 * @param {string} url - 图片的文件名，包括扩展名  
 * @returns {string} - 拼接后的OSS图片地址  
 */
export function OssUrl(url) {
	return HTTP_IMG_URL + url;
}
/**
 * @desc 全局提示函数
 * @param {string} title - 提示的内容
 * @param {string} icon - 图标名字
 * @param {number} endtime -提示的延迟时间，单位毫秒
 */
export function Toast(title, icon = 'none', endtime = 2000) {
	uni.showToast({
		title: title,
		icon: icon,
		duration: endtime
	});
}
/**
 * @desc 页面跳转函数
 * @param {object|string} opt - 提示的内容
 * @param {object|string} to_url - 页面跳转地址
 * 例:
 * this.$Tips('/pages/test/test'); 跳转不提示
 * this.$Tips({title:'提示'},'/pages/test/test'); 提示并跳转
 * this.$Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值table上
 */
const TAB_SWITCH = 1; //一定时间后跳转至 table上
const NAVIGATE = 2; //一定时间后跳转至非 table上
const NAVIGATE_BACK = 3; //一定时间后返回上页面
const RELAUNCH = 4; //关闭所有页面跳转至非table上
const REDIRECT = 5; //关闭当前页面跳转至table上
export function Tips(opt, to_url) {
	if (typeof opt == 'string') {
		to_url = opt;
		opt = {};
	}
	// 参数解构和默认值  
	const {
		title = '', icon = 'none', endtime = 2000
	} = opt;
	// 显示提示  
	if (title) Toast(title, icon, endtime)
	// 处理跳转逻辑  
	const handleRedirect = (delay, navigationFunc, navigationArgs) => {
		setTimeout(() => {
			navigationFunc(navigationArgs);
		}, delay);
	};
	if (to_url !== undefined) {
		if (typeof to_url === 'object') {
			const {
				tab = NAVIGATE, url = ''
			} = to_url;
			switch (tab) {
				case TAB_SWITCH:
					handleRedirect(endtime, uni.switchTab, {
						url
					});
					break;
				case NAVIGATE:
					handleRedirect(endtime, uni.navigateTo, {
						url
					});
					break;
				case NAVIGATE_BACK:
					const delta = parseInt(url, 10) || 1;
					handleRedirect(endtime, uni.navigateBack, {
						delta
					});
					break;
				case RELAUNCH:
					handleRedirect(endtime, uni.reLaunch, {
						url
					});
					break;
				case REDIRECT:
					handleRedirect(endtime, uni.redirectTo, {
						url
					});
					break;
				default:
					console.warn('Unsupported tab type:', tab);
			}
		} else if (typeof to_url === 'function') {
			handleRedirect(endtime, to_url, null);
		} else {
			// 直接跳转，不延迟  
			handleRedirect(title ? endtime : 0, uni.navigateTo, {
				url: to_url
			});
		}
	}
}
/**
 * @desc 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 */
export const Debounce = (fn, t) => {
	const delay = t || 500
	let timer
	return function() {
		const args = arguments
		if (timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			timer = null
			fn.apply(this, args)
		}, delay)
	}
}
/**
 * @desc 函数节流 每 几s 执行一次。
 * @param func 函数
 * @param wait 延迟执行毫秒数
 */
export const Throttle = (func, wait) => {
	let timeout;
	return function() {
		let context = this;
		let args = arguments;
		if (!timeout) {
			timeout = setTimeout(() => {
				timeout = null;
				func.apply(context, args)
			}, wait)
		}
	}
}
/**
 * @desc Base64图片数据上传
 * @param {string} base64Data - Base64格式的图片数据
 * @returns {Promise} - 返回上传结果Promise
 */
export function uploadBase64Image(base64Data) {
	return new Promise((resolve, reject) => {
		// 如果包含前缀，去除前缀
		const pureBase64 = base64Data.includes('base64,') ? base64Data.split('base64,')[1] : base64Data;
		const token = store.state.app.token;
		// 创建临时文件
		const filePath = `${Date.now()}.png`;
		const fileData = pureBase64;
		// 使用 uni.uploadFile 上传
		uni.uploadFile({
			url: HTTP_REQUEST_URL + '/api/common/upload',
			filePath: base64Data,
			name: 'file',
			formData: {
				'base64': fileData
			},
			header: {
				'token': token
			},
			success: (uploadFileRes) => {
				try {
					const res = JSON.parse(uploadFileRes.data);
					console.log('上传响应：', res);
					if (res.code == 1) {
						resolve(res.data);
					} else {
						reject(res.msg || '上传失败');
					}
				} catch (e) {
					reject('解析返回数据失败');
				}
			},
			fail: (err) => {
				console.error('上传失败：', err);
				reject(err);
			}
		});
	});
}
// 缓存视频 返回文件url
export async function cacheVideo(video) {
	
	// #ifdef APP
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: video.url,
			success: async (res) => {
				// const savedFilePath = await saveVideoToLocal(res.tempFilePath, video.id);
				uni.saveFile({
					tempFilePath:res.tempFilePath,
					success: (res) => {
						resolve(res.savedFilePath)
					},
					fail() {
						reject(video.url)
					}
				})
			},
			fail: () => {
				reject(video.url)
			}
		})
	})
	//#endif
	//#ifdef H5
	return new Promise(async (resolve, reject)=>{
		try {
			const response = await fetch(video.url);
			const blob = await response.blob();
			const blobUrl = URL.createObjectURL(blob);
			resolve(blobUrl)
		} catch (error) {
			console.log(error);
			reject(error)
		}
		// uni.request({
		// 	url:video.url,
		// 	method:'GET',
		// 	responseType:'blob',
		// 	header:{
		// 		'Access-Control-Allow-Origin':"*"
		// 	},
		// 	success: (res) => {
				
		// 		console.log(res);
		// 		const blob = new Blob([res.data], { type: 'video/mp4' });
		// 		resolve(URL.createObjectURL(blob))
		// 	},
		// 	fail: (err) => {
		// 		console.log(err);
		// 	}
		// })
	})
	//#endif
}
// 保存视频到本地
function saveVideoToLocal(tempFilePath, videoId) {
	return new Promise((resolve, reject) => {
		// #ifdef APP-PLUS
		const appBaseInfo = uni.getAppBaseInfo();
		console.log(appBaseInfo.appId);
		console.log(plus.io.convertLocalFileSystemURL('_documents'));
		// 获取应用存储目录
		const baseDir = plus.io.convertLocalFileSystemURL(plus.io.PRIVATE_WWW) + '/cached_videos/';
		console.log(baseDir);
		// 检查目录是否存在
		plus.io.resolveLocalFileSystemURL(baseDir, (entry) => {
			console.log('saveFile2');
			saveFile(tempFilePath, baseDir + videoId + '.mp4', resolve, reject);
		}, () => {
			console.log(plus.io.convertLocalFileSystemURL(''));
			// 目录不存在则创建
			plus.io.resolveLocalFileSystemURL('_documents/', (rootEntry) => {
				rootEntry.getDirectory('cached_videos', {
					create: true
				}, (dirEntry) => {
					console.log('saveFile');
					saveFile(tempFilePath, baseDir + videoId + '.mp4', resolve, reject);
				}, (err)=>{
					console.log(err);
				});
			}, (err)=>{
				console.log(err);
			});
		});
		// #endif
		// #ifndef APP-PLUS
		reject(new Error('仅支持APP端'));
		// #endif
	});
}
// 保存文件
function saveFile(tempFilePath, filePath, resolve, reject,videoId) {
	plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
		// 文件已存在，直接返回路径
		resolve(filePath);
	}, () => {
		// 文件不存在，移动临时文件
		plus.io.resolveLocalFileSystemURL(tempFilePath, (tempEntry) => {
			tempEntry.copyTo(plus.io.convertLocalFileSystemURL('_doc/cached_videos/'), videoId + '.mp4', (newEntry) => {
				console.log('aaaa');
				resolve(newEntry.fullPath);
			}, (c) => {
				console.log(c);
			});
		}, reject);
	});
}
// 清理缓存
function clearCache() {
	uni.showModal({
		title: '提示',
		content: '确定要清理所有缓存视频吗？',
		success: (res) => {
			if (res.confirm) {
				doClearCache()
			}
		}
	});
}
// 执行缓存清理
export async function doClearCache() {
	try {
		// #ifdef APP-PLUS
		// 删除缓存目录
		const dirPath = '_doc/uniapp_save/';
		plus.io.resolveLocalFileSystemURL(dirPath, (entry) => {
			entry.removeRecursively(() => {console.log('清空缓存成功')}, (error) => {
				console.error('清理缓存失败:', error);
			});
		}, () => {});
		// #endif
	} catch (error) {
		console.error('清理缓存失败:', error);
	}
}
export function checkOpenGPSService() {
	//#ifdef APP
	let systemType = uni.getSystemInfoSync().platform;
	// 安卓
	if (systemType === 'android') {
		var main = plus.android.runtimeMainActivity();
		var context = plus.android.importClass('android.content.Context');
		var locationManager = plus.android.importClass('android.location.LocationManager');
		var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
		return !mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)
	}
	//#endif
	return true
}
export function openSeting(){
	//#ifdef APP
	var main = plus.android.runtimeMainActivity();
	var Intent = plus.android.importClass('android.content.Intent');
	var Settings = plus.android.importClass('android.provider.Settings');
	var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	main.startActivity(intent); 
	//#endif
}